package com.mikhailenko.transportMVC.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mikhailenko.transportMVC.exeption.FirmNotFoundExeption;
import com.mikhailenko.transportMVC.model.Firm;
import com.mikhailenko.transportMVC.repository.FirmRepository;
import com.mikhailenko.transportMVC.service.FirmService;

@Service
public class FirmServiceImpl implements FirmService{

	@Autowired
	private FirmRepository firmRepository;
	
	@Override
	@Transactional
	public Firm create(Firm firm) {
		Firm createdFrim = firm;
		return firmRepository.saveAndFlush(createdFrim);
	}

	@Override
	@Transactional(rollbackFor=FirmNotFoundExeption.class)
	public Firm delete(int id) throws FirmNotFoundExeption {
		Firm deletedFirm = new Firm();
		deletedFirm =  firmRepository.findOne(id);
		
		if (deletedFirm == null){
			throw new FirmNotFoundExeption();
		}
		
		firmRepository.delete(id);
		return deletedFirm;
	}

	@Override
	@Transactional
	public List<Firm> findAll() {
		return firmRepository.findAll();
	}

	@Override
	@Transactional(rollbackFor=FirmNotFoundExeption.class)
	public Firm update(Firm firm) throws FirmNotFoundExeption {
		Firm updatedFirm = firmRepository.findOne(firm.getId());
		
		if (updatedFirm == null){
			throw new FirmNotFoundExeption();
		}
			
		updatedFirm.setName(firm.getName());
		updatedFirm.setTelephone(firm.getTelephone());
		updatedFirm.setAddress(firm.getAddress());
		return updatedFirm;
	}

	@Override
	@Transactional
	public Firm findById(int id) {
		return firmRepository.findOne(id);
	}

	@Override
	public Firm findByName(String name) {
		return firmRepository.findByName(name);
	}

}
